package yxy.game.pm2.bean.db.dao;

import java.util.*;

import yxy.apple.database.BaseDAO;
import yxy.apple.database.DAOManager;
import yxy.game.pm2.bean.db.module.account;
import yxy.game.pm2.bean.db.module.player;
import yxy.game.pm2.bean.db.module.server;

public class MySQLPlayerDAO extends BaseDAO<player> {

	/** 账号下的角色数 */
	public static int size(int accountId) {
		try {
			String sql = String.format("select count(accountid) from player where accountid = %d", accountId);
			return getCount(DAOManager.getGameH(), sql, null);
		} catch (Exception e) {
			return -1;
		}
	}

	/** 账号下的角色列表 */
	public static List<player> all(int accountId) {
		String sql = String.format("from player as ts where ts.accountid = %d", accountId);
		return query(DAOManager.getGameH(), sql, null);
	}

	public static player get(int id) {
		return get(DAOManager.getGameH(), server.class, id);
	}

	public static player get(int accountId, int serverId) {
		String sql = String.format("from player as ts where ts.accountid = %d and ts.serverid = %d", accountId, serverId);
		return queryOne(DAOManager.getGameH(), sql, null);
	}

	public static boolean add(player db) {
		return MySQLPlayerDAO.add(DAOManager.getGameH(), db);
	}

	public static void setName(String playerCode, String name) {
		String sql = String.format("from player where code = '%s'", playerCode);
		player db = queryOne(DAOManager.getGameH(), sql, null);
		if (db == null) {
			return;
		}
		db.setName(name);
		update(DAOManager.getGameH(), db);
	}

	public static boolean checkNameIsUsed(String name) {
		String sql = String.format("from player where name = '%s'", name);
		player db = queryOne(DAOManager.getGameH(), sql, null);
		if (db == null) {
			return false;
		}
		return true;
	}

	public static player getByName(String name) {
		String sql = String.format("from player where name = '%s'", name);
		player db = queryOne(DAOManager.getGameH(), sql, null);
		if (db == null) {
			return null;
		}
		return db;
	}

	//查找同一个专服内的玩家
	public static Collection<player> search(int clusterId, ArrayList<String> serverIds, String keyword, int size) {
		try {
			Map<String, Object> params = new Hashtable<>();
			params.put("name", "%" + keyword + "%");
			params.put("clusterid", clusterId);
			params.put("limit", size);
			String sql = "select p.* from player p inner join account a on p.accountid = a.id where a.clusterid=:clusterid";

			//同时根据服id查找
			if (serverIds != null && serverIds.size() > 0) {
				params.put("serverIds", serverIds);
				sql += " and p.serverid in (:serverIds)";
			}

			sql += " and p.name like :name limit :limit";
			List<player> list = queryBySql(DAOManager.getGameH(), player.class, sql, params);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

//		String sql = String.format("from player where name like '%%%s%%'", keyword);
//		return queryLimit(DAOManager.getGameH(), sql, null, size);
	}

}
